import 'dart:convert';
import 'dart:math';

import 'package:concierge/app/routes/app_routes.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:http/http.dart' as http;

import '../../widgets/ms_app_bar.dart';

class WebViewDemo extends GetView {
  const WebViewDemo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MSAppBar(title: const Text('WebView演示')),
      backgroundColor: context.theme.colorScheme.onPrimaryContainer,
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          ListTile(
            title: const Text('VERTU 官网'),
            subtitle: const Text('https://www.vertu.cn/'),
            leading: const Icon(Icons.search),
            onTap: () {
              Get.toNamed(
                Routes.enhancedWeb,
                arguments: {
                  'url': 'https://www.vertu.cn/',
                  'title': 'VERTU 官网',
                },
              );
            },
          ),
          const Divider(),
          ListTile(
            title: const Text('百度'),
            subtitle: const Text('https://www.baidu.com'),
            leading: const Icon(Icons.language),
            onTap: () {
              Get.toNamed(
                Routes.enhancedWeb,
                arguments: {'url': 'https://www.baidu.com', 'title': '百度'},
              );
            },
          ),
          const Divider(),
          ListTile(
            title: const Text('GitHub'),
            subtitle: const Text('https://github.com'),
            leading: const Icon(Icons.code),
            onTap: () {
              Get.toNamed(
                Routes.enhancedWeb,
                arguments: {'url': 'https://github.com', 'title': 'GitHub'},
              );
            },
          ),
          const Divider(),
          ListTile(
            title: const Text('Google登录'),
            subtitle: const Text(''),
            leading: const Icon(Icons.code),
            onTap: () async {
              const String _backendAuthEndpoint =
                  'https://your-domain.com/api/auth/google'; // 你的PHP后端接收code的API

              const String clientId =
                  '25516843599-t6uap71plbunlegfc27uk83d0n8kaent.apps.googleusercontent.com'; // 从GCP控制台获取
              const String redirectUri =
                  'https://life-api.vertu.cn/test/v3/auth/google'; // 与原生配置一致

              const String scope = 'openid email profile'; // 请求的用户信息范围

              // 构建认证请求URL
              final String authUrl =
                  'https://accounts.google.com/o/oauth2/v2/auth?'
                  'response_type=code&'
                  'client_id=$clientId&'
                  'redirect_uri=${Uri.encodeComponent(redirectUri)}&'
                  'scope=openid%20email%20profile&' // 请求访问邮箱和基本资料
                  'state=random_string_123'; // 可选，用于防止CSRF攻击

              try {
                // 3. 跳转到浏览器进行登录授权
                final result =
                    await FlutterWebAuth2.authenticate(
                      url: authUrl,
                      callbackUrlScheme: Uri.parse(redirectUri).scheme,
                    ).then((result) {
                      Get.back(); // 关闭浏览器返回原页面
                      return result;
                    });

                print("Raw result from FlutterWebAuth2: $result");

                // 4. 从重定向回来的URL中解析出授权码 `code`
                final Uri returnedUri = Uri.parse(result);
                print("Returned URI: $returnedUri");
                print("Query parameters: ${returnedUri.queryParameters}");
                final String? authorizationCode =
                    returnedUri.queryParameters['code'];

                if (authorizationCode == null) {
                  throw Exception('Authorization code not found');
                }
                print("authorizationCode:$authorizationCode");

                // 5. 将授权码发送给自己的后端
                final http.Response response = await http.post(
                  Uri.parse(_backendAuthEndpoint),
                  body: json.encode({'code': authorizationCode}),
                  headers: {'Content-Type': 'application/json'},
                );

                // 6. 处理后端返回的token和用户信息
                if (response.statusCode == 200) {
                  final Map<String, dynamic> responseData = json.decode(
                    response.body,
                  );
                  final String jwtToken = responseData['token'];
                  final userData = responseData['user'];

                  // 保存JWT token到本地存储（如shared_preferences），用于后续API请求
                  print('Login Success! JWT: $jwtToken, User: $userData');
                } else {
                  // 处理错误
                  print('Backend error: ${response.body}');
                }
              } catch (e) {
                print('Sign in failed: $e');
              }
            },
          ),

          const Divider(),
          ListTile(
            title: const Text('Google登录'),
            subtitle: const Text(''),
            leading: const Icon(Icons.code),
            onTap: () async {
              const String _backendAuthEndpoint =
                  'https://your-domain.com/api/auth/google'; // 你的PHP后端接收code的API

              const String clientId =
                  '25516843599-t6uap71plbunlegfc27uk83d0n8kaent.apps.googleusercontent.com'; // 从GCP控制台获取
              const String redirectUri =
                  'https://life-api.vertu.cn/test/v3/auth/google'; // 与原生配置一致

              const String scope = 'openid email profile'; // 请求的用户信息范围

              // 构建认证请求URL
              final String authUrl =
                  'https://accounts.google.com/o/oauth2/v2/auth?'
                  'response_type=code&'
                  'client_id=$clientId&'
                  'redirect_uri=${Uri.encodeComponent(redirectUri)}&'
                  'scope=openid%20email%20profile&' // 请求访问邮箱和基本资料
                  'state=random_string_123'; // 可选，用于防止CSRF攻击

              try {
                // 3. 跳转到浏览器进行登录授权
                final result =
                    await FlutterWebAuth2.authenticate(
                      url: authUrl,
                      callbackUrlScheme: Uri.parse(redirectUri).scheme,
                    ).then((result) {
                      Get.back(); // 关闭浏览器返回原页面
                      return result;
                    });

                print("Raw result from FlutterWebAuth2: $result");

                // 4. 从重定向回来的URL中解析出授权码 `code`
                final Uri returnedUri = Uri.parse(result);
                print("Returned URI: $returnedUri");
                print("Query parameters: ${returnedUri.queryParameters}");
                final String? authorizationCode =
                    returnedUri.queryParameters['code'];

                if (authorizationCode == null) {
                  throw Exception('Authorization code not found');
                }
                print("authorizationCode:$authorizationCode");

                // 5. 将授权码发送给自己的后端
                final http.Response response = await http.post(
                  Uri.parse(_backendAuthEndpoint),
                  body: json.encode({'code': authorizationCode}),
                  headers: {'Content-Type': 'application/json'},
                );

                // 6. 处理后端返回的token和用户信息
                if (response.statusCode == 200) {
                  final Map<String, dynamic> responseData = json.decode(
                    response.body,
                  );
                  final String jwtToken = responseData['token'];
                  final userData = responseData['user'];

                  // 保存JWT token到本地存储（如shared_preferences），用于后续API请求
                  print('Login Success! JWT: $jwtToken, User: $userData');
                } else {
                  // 处理错误
                  print('Backend error: ${response.body}');
                }
              } catch (e) {
                print('Sign in failed: $e');
              }
            },
          ),
          //todo---------------------------------------------
          ListTile(
            title: const Text('Google登录测试 PKCE'),
            subtitle: const Text('https://github.com'),
            leading: const Icon(Icons.code),
            onTap: () async {
              try {
                const String clientId =
                    '25516843599-cor8cberhgb1ih2gffsiup4dd1q8q070.apps.googleusercontent.com'; // 从GCP控制台获取

                final redirectUri = "com.vertu.concierge:/oauth2redirect";
                const String scope = 'openid email profile'; // 请求的用户信息范围

                // 1. 生成PKCE参数
                final rand = Random.secure();
                final values = List<int>.generate(32, (_) => rand.nextInt(256));
                final codeVerifier = base64UrlEncode(
                  values,
                ).replaceAll("=", "");

                final bytes = utf8.encode(codeVerifier);
                final digest = sha256.convert(bytes);
                final codeChallenge = base64UrlEncode(
                  digest.bytes,
                ).replaceAll("=", "");

                // 2. 构建授权URL
                final authUrl =
                    'https://accounts.google.com/o/oauth2/v2/auth'
                    '?response_type=code'
                    '&client_id=$clientId'
                    '&redirect_uri=$redirectUri'
                    '&scope=$scope'
                    '&code_challenge=$codeChallenge'
                    '&code_challenge_method=S256';

                // 3. 使用FlutterWebAuth2进行认证
                final result = await FlutterWebAuth2.authenticate(
                  url: authUrl,
                  callbackUrlScheme: 'com.vertu.concierge',
                );

                // 4. 获取授权码
                final code = Uri.parse(result).queryParameters['code'];
                if (code == null) throw Exception('未获取到授权码');

                print('获取到授权码: $code');

                // 5. 请求访问令牌
                final response = await http.post(
                  Uri.parse('https://oauth2.googleapis.com/token'),
                  headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                  },
                  body: {
                    'grant_type': 'authorization_code',
                    'code': code,
                    'client_id': clientId,
                    'redirect_uri': redirectUri,
                    'code_verifier': codeVerifier,
                  },
                );

                final body = json.decode(response.body);
                final accessToken = body['access_token'];

                print('获取到访问令牌: $accessToken');

                // 显示成功消息
                Get.snackbar('登录成功', '已获取访问令牌');
              } catch (e) {
                print('PKCE登录失败: $e');
                Get.snackbar('登录失败', '错误: $e');
              }
            },
          ),

          const Divider(),
          ListTile(
            title: const Text('Goole login'),
            subtitle: const Text('https://github.com'),
            leading: const Icon(Icons.code),
            onTap: () async {
              try {
                final GoogleSignIn googleSignIn = GoogleSignIn.instance;

                await googleSignIn.initialize(
                  // clientId:
                  //     '25516843599-cor8cberhgb1ih2gffsiup4dd1q8q070.apps.googleusercontent.com',
                  serverClientId:
                      '25516843599-t6uap71plbunlegfc27uk83d0n8kaent.apps.googleusercontent.com',
                  hostedDomain: 'life-api.vertu.cn',
                );

                // 执行认证并在authenticate方法中指定作用域
                var account = await googleSignIn
                    .attemptLightweightAuthentication();

                // final GoogleSignInAccount? account =
                //     await googleSignIn.authenticate(
                //   scopeHint: [
                //     'email',
                //     'profile',
                //   ],
                // );

                if (account != null) {
                  // 获取用户信息
                  final GoogleSignInAuthentication auth =
                      await account.authentication;

                  print('登录成功: ${account.displayName}');
                  print('邮箱: ${account.email}');
                  print('ID: ${account.id}');
                  print('访问令牌: ${auth.idToken}');
                  //打印account 全部内容
                  print('account信息: $account');
                  print('account.authentication信息: $auth');

                  // 显示成功消息
                  Get.snackbar(
                    '登录成功',
                    '欢迎, ${account.displayName}!',
                    snackPosition: SnackPosition.BOTTOM,
                  );

                  // 可以在这里处理用户信息，比如保存到本地或发送到服务器
                } else {
                  Get.snackbar(
                    '登录取消',
                    '用户取消了登录',
                    snackPosition: SnackPosition.BOTTOM,
                  );
                }
              } catch (e) {
                print('Google登录失败: $e');
                Get.snackbar(
                  '登录失败',
                  '错误: ${e.toString()}',
                  snackPosition: SnackPosition.BOTTOM,
                );
              }
            },
          ),

          const Divider(),
          ListTile(
            title: const Text('自定义网址'),
            subtitle: const Text('输入任意网址'),
            leading: const Icon(Icons.edit),
            onTap: () {
              showDialog(
                context: context,
                builder: (context) {
                  final urlController = TextEditingController();
                  final titleController = TextEditingController();
                  return AlertDialog(
                    backgroundColor: context.theme.primaryColorDark,
                    title: const Text('打开网页'),
                    content: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        TextField(
                          controller: urlController,
                          decoration: const InputDecoration(
                            labelText: '网址',
                            hintText: 'https://example.com',
                          ),
                        ),
                        const SizedBox(height: 16),
                        TextField(
                          controller: titleController,
                          decoration: const InputDecoration(
                            labelText: '标题（可选）',
                            hintText: '网页标题',
                          ),
                        ),
                      ],
                    ),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.pop(context),
                        child: const Text('取消'),
                      ),
                      ElevatedButton(
                        onPressed: () {
                          if (urlController.text.isNotEmpty) {
                            Navigator.pop(context);
                            Get.toNamed(
                              Routes.enhancedWeb,
                              arguments: {
                                'url': urlController.text,
                                'title': titleController.text.isNotEmpty
                                    ? titleController.text
                                    : '网页浏览',
                              },
                            );
                          }
                        },
                        child: const Text('打开'),
                      ),
                    ],
                  );
                },
              );
            },
          ),
          const Divider(),
          ListTile(
            title: const Text('JavaScript通信测试'),
            subtitle: const Text('测试Flutter与JavaScript的双向通信'),
            leading: const Icon(Icons.sync),
            onTap: () {
              Get.toNamed(
                Routes.enhancedWeb,
                arguments: {
                  'url':
                      'data:text/html;charset=utf-8,'
                      '<html>'
                      '<head>'
                      '<title>JavaScript通信测试</title>'
                      '<style>'
                      'body { font-family: Arial, sans-serif; padding: 20px; }'
                      'button { padding: 10px 20px; margin: 5px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; }'
                      'button:hover { background: #0056b3; }'
                      '.result { margin-top: 20px; padding: 10px; background: #f8f9fa; border-radius: 5px; }'
                      '</style>'
                      '</head>'
                      '<body>'
                      '<h2>JavaScript与Flutter通信测试</h2>'
                      '<button onclick="callFlutter()">调用Flutter方法</button>'
                      '<button onclick="testAlert()">测试Alert方法</button>'
                      '<button onclick="testAllMethods()">测试所有本地方法</button>'
                      '<div class="result" id="result">等待操作...</div>'
                      '<script>'
                      'function callFlutter() {'
                      '  if (window.FlutterJSChannel) {'
                      '    window.FlutterJSChannel.callFlutter("Hello from JavaScript!");'
                      '    document.getElementById("result").innerHTML = "已调用Flutter方法";'
                      '  } else {'
                      '    document.getElementById("result").innerHTML = "Flutter通信桥未初始化";'
                      '  }'
                      '}'
                      'function testAlert() {'
                      '  if (window.FlutterJSChannel) {'
                      '    const result = window.FlutterJSChannel.callJavaScriptMethod("showAlert", "这是一个测试消息");'
                      '    document.getElementById("result").innerHTML = "Alert测试结果: " + result;'
                      '  } else {'
                      '    document.getElementById("result").innerHTML = "Flutter通信桥未初始化";'
                      '  }'
                      '}'
                      'function testAllMethods() {\n'
                      '  if (window.flutter_inappwebview) {\n'
                      '    // 测试showToast方法\n'
                      '    window.flutter_inappwebview.callHandler("showToast", "Hello from JavaScript!");\n'
                      '    \n'
                      '    // 测试getDeviceInfo方法\n'
                      '    window.flutter_inappwebview.callHandler("getDeviceInfo").then(result => {\n'
                      '      console.log("设备信息:", result);\n'
                      '      document.getElementById("result").innerHTML = "设备信息: " + JSON.stringify(result);\n'
                      '    });\n'
                      '    \n'
                      '    // 测试calculate方法（带多个参数）\n'
                      '    window.flutter_inappwebview.callHandler("calculate", 10, 5, "multiply").then(result => {\n'
                      '      console.log("计算结果:", result);\n'
                      '    });\n'
                      '    \n'
                      '    // 测试saveUserData方法（带复杂对象参数）\n'
                      '    const userData = {\n'
                      '      name: "张三",\n'
                      '      age: 25,\n'
                      '      email: "zhangsan@example.com"\n'
                      '    };\n'
                      '    window.flutter_inappwebview.callHandler("saveUserData", userData).then(result => {\n'
                      '      console.log("保存结果:", result);\n'
                      '    });\n'
                      '  } else {\n'
                      '    document.getElementById("result").innerHTML = "Flutter通信桥未初始化";\n'
                      '  }\n'
                      '}'
                      '</script>'
                      '</body>'
                      '</html>',
                  'title': 'JavaScript通信测试',
                },
              );
            },
          ),
          const Divider(),
          ListTile(
            title: const Text('完整通信测试页面'),
            subtitle: const Text('访问完整的双向通信测试界面'),
            leading: const Icon(Icons.integration_instructions),
            onTap: () {
              Get.toNamed(
                Routes.enhancedWeb,
                arguments: {
                  'url':
                      'file:///android_asset/flutter_assets/assets/test_communication.html',
                  'title': '完整通信测试',
                },
              );
            },
          ),
        ],
      ),
    );
  }
}
